//
//  UIViewController+WSJLodingView.m
//  HandheldELearn
//
//  Created by wsj2015 on 16/7/16.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "UIViewController+WSJLodingView.h"
#import <Accelerate/Accelerate.h>
#import "JCAlertView.h"
#import "DNOLabelAnimation.h"
#import "WSJLoadFailedView.h"
#define JCiOS7OrLater ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
@implementation UIViewController (WSJLodingView)



- (void)wsj_showLodingGif{

   
    UIView *maskView =[UIView new];
    maskView.backgroundColor =[UIColor clearColor];
    maskView.frame = self.view.bounds;
    maskView.tag = 101;
    [self.view addSubview:maskView];
   
    UIImageView *imageView = [UIImageView new];
   
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 1; i<9; i ++) {
        @autoreleasepool {
            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"animated%d",i]];
            [arr addObject:image];
        }
        
    }
    
    imageView.tag = 6001;
    imageView.animationImages = arr;
    [imageView sizeToFit];
    imageView.center = CGPointMake(kScreenWidth/2, kScreenHeight/2 - 64);
    [imageView startAnimating];
    
    NSDictionary *attribute = @{NSForegroundColorAttributeName : [UIColor whiteColor],NSFontAttributeName : [UIFont systemFontOfSize:15]};
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"努力加载中..." attributes:attribute];
    DNOLabelAnimation *textView = [[DNOLabelAnimation alloc] initWithFrame:CGRectMake(CGRectGetMinX(imageView.frame)+ 20, CGRectGetMaxY(imageView.frame)+2, 0, 0) attributedText:string];
    
    textView.type = DNOLabelAnimationTypeWave;
    textView.font = [UIFont fontWithName:@"Courier" size:15];
    textView.tag = 200;
    textView.textColor = [UIColor whiteColor];
    textView.rate = 7;
    [textView sizeToFit];
 
    [textView startAnimation];
    [self addScreenShot];
    [self.view addSubview:imageView];
    [self.view addSubview:textView];
  
    
}
- (void)wsj_hideLodingGif{
    

    UIView *loadingView =[self.view viewWithTag:9001] ;
    UIView *maskView =[self.view viewWithTag:101] ;
    UIImageView *imageView = [self.view viewWithTag:6001];
    DNOLabelAnimation *label = [self.view viewWithTag:200];
    if (!loadingView) {
        return;
    }
    
    [imageView stopAnimating];
    [label stopAnimation];
    [UIView animateWithDuration:.34 animations:^{
        loadingView.alpha = 0.0001;
    } completion:^(BOOL finished) {
        [imageView removeFromSuperview];
        [maskView removeFromSuperview];
        [loadingView removeFromSuperview];
        [label removeFromSuperview];
    }];
    
   


}
- (UIView *)addScreenShot{
    UIWindow *screenWindow = [UIApplication sharedApplication].windows.firstObject;
    UIGraphicsBeginImageContext(screenWindow.frame.size);
    [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImage *originalImage = nil;
    if (JCiOS7OrLater) {
        originalImage = viewImage;
    } else {
        originalImage = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(viewImage.CGImage, CGRectMake(0, 20, kScreenWidth, kScreenHeight))];
    }
    
    CGFloat blurRadius = 4;
    UIColor *tintColor = [UIColor colorWithWhite:.4 alpha:.8];
    CGFloat saturationDeltaFactor = 1;
    UIImage *maskImage = nil;
    
    CGRect imageRect = { CGPointZero, originalImage.size };
    UIImage *effectImage = originalImage;
    
    BOOL hasBlur = blurRadius > __FLT_EPSILON__;
    BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__;
    if (hasBlur || hasSaturationChange) {
        UIGraphicsBeginImageContextWithOptions(originalImage.size, NO, [[UIScreen mainScreen] scale]);
        CGContextRef effectInContext = UIGraphicsGetCurrentContext();
        CGContextScaleCTM(effectInContext, 1.0, -1.0);
        CGContextTranslateCTM(effectInContext, 0, -originalImage.size.height);
        CGContextDrawImage(effectInContext, imageRect, originalImage.CGImage);
        
        vImage_Buffer effectInBuffer;
        effectInBuffer.data	 = CGBitmapContextGetData(effectInContext);
        effectInBuffer.width	= CGBitmapContextGetWidth(effectInContext);
        effectInBuffer.height   = CGBitmapContextGetHeight(effectInContext);
        effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext);
        
        UIGraphicsBeginImageContextWithOptions(originalImage.size, NO, [[UIScreen mainScreen] scale]);
        CGContextRef effectOutContext = UIGraphicsGetCurrentContext();
        vImage_Buffer effectOutBuffer;
        effectOutBuffer.data	 = CGBitmapContextGetData(effectOutContext);
        effectOutBuffer.width	= CGBitmapContextGetWidth(effectOutContext);
        effectOutBuffer.height   = CGBitmapContextGetHeight(effectOutContext);
        effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext);
        
        if (hasBlur) {
            CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale];
            uint32_t radius = floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5);
            if (radius % 2 != 1) {
                radius += 1;
            }
            vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
            vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
            vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
        }
        BOOL effectImageBuffersAreSwapped = NO;
        if (hasSaturationChange) {
            CGFloat s = saturationDeltaFactor;
            CGFloat floatingPointSaturationMatrix[] = {
                0.0722 + 0.9278 * s,  0.0722 - 0.0722 * s,  0.0722 - 0.0722 * s,  0,
                0.7152 - 0.7152 * s,  0.7152 + 0.2848 * s,  0.7152 - 0.7152 * s,  0,
                0.2126 - 0.2126 * s,  0.2126 - 0.2126 * s,  0.2126 + 0.7873 * s,  0,
                0,					0,					0,  1,
            };
            const int32_t divisor = 256;
            NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]);
            int16_t saturationMatrix[matrixSize];
            for (NSUInteger i = 0; i < matrixSize; ++i) {
                saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor);
            }
            if (hasBlur) {
                vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
                effectImageBuffersAreSwapped = YES;
            }
            else {
                vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
            }
        }
        if (!effectImageBuffersAreSwapped)
            effectImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        if (effectImageBuffersAreSwapped)
            effectImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    UIGraphicsBeginImageContextWithOptions(originalImage.size, NO, [[UIScreen mainScreen] scale]);
    CGContextRef outputContext = UIGraphicsGetCurrentContext();
    CGContextScaleCTM(outputContext, 1.0, -1.0);
    CGContextTranslateCTM(outputContext, 0, -originalImage.size.height);
    
    CGContextDrawImage(outputContext, imageRect, originalImage.CGImage);
    
    if (hasBlur) {
        CGContextSaveGState(outputContext);
        if (maskImage) {
            CGContextClipToMask(outputContext, imageRect, maskImage.CGImage);
        }
        CGContextDrawImage(outputContext, imageRect, effectImage.CGImage);
        CGContextRestoreGState(outputContext);
    }
    
    if (tintColor) {
        CGContextSaveGState(outputContext);
        CGContextSetFillColorWithColor(outputContext, tintColor.CGColor);
        CGContextFillRect(outputContext, imageRect);
        CGContextRestoreGState(outputContext);
    }
    
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
 
    UIImageView *bgView = [[UIImageView alloc] initWithImage:outputImage];
    bgView.tag = 9001;
    [self.view addSubview:bgView];
    return bgView;
}

- (void)wsj_showLoadFailviewWithRetry:(void (^)())retry{
    
    [WSJLoadFailedView showLoadFailedInView:self.view retryHandle:retry];

}


@end
